package org.chaos.utils.transaction;

import org.chaos.utils.bean.BeanUtil;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class TransUtils {
    private static DefaultTransactionDefinition txDefinition;
    static {
        txDefinition = new DefaultTransactionDefinition();
        txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    }

    public static Transaction getTrans() {
        Transaction ut = new MyTransaction();
        PlatformTransactionManager transactionManager = BeanUtil.getBean("transactionManager",PlatformTransactionManager.class);

        ut.setTxManager(transactionManager);
        ut.setTransactionDefinition(txDefinition);
        return ut;
    }

    public static void commit(Transaction trans) {
        if(null != trans) {
            try {
                trans.commit();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void rollback(Transaction trans) {
        if(null != trans) {
            try {
                trans.rollback();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
